package com.bbs.utils;

import javax.mail.Message;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

public class MailUtils {
    private static final String USER = "weijbo@163.com";
    private static final String PASSWORD = "JNCNASTFXJTAPQLJ";
    /**
     *
     * @param to 收件人邮箱
     * @param text 邮件正文
     * @param title 标题
     */
    /* 发送验证信息的邮件 */
    public static boolean sendMail(String to, String text, String title){
        try {
            // put方法是往集合中添加一对键值对
            final Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.host", "smtp.163.com");
            props.put("mail.smtp.port", "587");

            // 发件人的账号
            props.put("mail.user", USER);
            //发件人的密码
            props.put("mail.password", PASSWORD);

            // 构建授权信息，进行身份验证
            MyAuthenticator authenticator = new MyAuthenticator();

            // 使用环境属性和授权信息，创建邮件会话
            Session mailSession = Session.getInstance(props,authenticator);
            // 创建邮件消息
            MimeMessage message = new MimeMessage(mailSession);
            // 设置发件人
            String username = props.getProperty("mail.user");
            InternetAddress form = new InternetAddress(username);
            message.setFrom(form);

            // 设置收件人
            InternetAddress toAddress = new InternetAddress(to);
            message.setRecipient(Message.RecipientType.TO, toAddress);

            // 设置邮件标题
            message.setSubject(title);

            // 设置邮件的内容体
            message.setContent(text, "text/html;charset=UTF-8");
            // 发送邮件
            Transport.send(message);
//            System.out.println("发送成功");
            return true;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;

    }

    public static void main(String[] args) {
        MailUtils.sendMail("723159401@qq.com",
                "激活链接 http://localhost:8080/ssm_bbs_war/activatUser?email=bbb@qq.com&activateCode=705869",
                "用户激活邮件");
    }
}
